package com.yeskery.nut.bean.condition;

import com.yeskery.nut.annotation.condition.ConditionalOnPlugin;
import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.bean.AnnotationApplicationContext;
import com.yeskery.nut.plugin.Plugin;
import com.yeskery.nut.scan.BeanAnnotationScanMetadata;

import java.util.Arrays;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * 插件存在条件判断，部分插件方式无法通过该判断
 * @author sunjay
 * 2023/9/6
 */
public class OnPluginCondition implements Condition {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(OnPluginCondition.class.getName());

    @Override
    public boolean matches(NutApplication nutApplication, Collection<BeanAnnotationScanMetadata> beanAnnotationScanMetadata, Object conditionalAnnotation) {
        ConditionalOnPlugin conditionalOnPlugin = (ConditionalOnPlugin) conditionalAnnotation;
        boolean result = doMatches(nutApplication, beanAnnotationScanMetadata, conditionalOnPlugin.value());
        if (!result && logger.isLoggable(Level.FINEST)) {
            logger.log(Level.FINEST, "Plugin Condition Not Match, Condition[" + this.getClass().getName()
                    + "], Expect Plugin Found[" + Arrays.stream(conditionalOnPlugin.value()).map(Class::getName).collect(Collectors.joining(", "))
                    + "], Actual Plugin Not Found.");
        }
        return result;
    }

    /**
     * 判断bean是否匹配的方法
     * @param nutApplication Nut应用对象
     * @param beanAnnotationScanMetadata 所有Bean扫描元数据类型
     * @param classes 插件类型数组
     * @return bean是否匹配的方法
     */
    protected boolean doMatches(NutApplication nutApplication, Collection<BeanAnnotationScanMetadata> beanAnnotationScanMetadata,
                                Class<? extends Plugin>[] classes) {
        AnnotationApplicationContext annotationApplicationContext = (AnnotationApplicationContext) nutApplication.getApplicationContext();
        for (Class<? extends Plugin> pluginClass : classes) {
            if (nutApplication.getNutWebConfigure().getPluginManager().containPlugin(pluginClass)) {
                continue;
            }
            if (annotationApplicationContext.getBeans(pluginClass).isEmpty()) {
                annotationApplicationContext.registerBean(pluginClass);
                if (annotationApplicationContext.getBeans(pluginClass).isEmpty()) {
                    return false;
                }
            }
        }
        return true;
    }
}
